const Video = require('../models/video.model')
const User = require('../models/user.model') 
const path = require('path')
const fs = require('fs')
const ffmpeg = require('fluent-ffmpeg')
const { validationResult } = require('express-validator');

// 处理视频上传
const processVideo = async (videoId, originalVideoPath) => {
  console.log(`[${videoId}] 开始处理视频: ${originalVideoPath}`);
  let video;
  try {
    video = await Video.findById(videoId);
    if (!video) {
      throw new Error('视频不存在');
    }

    try {
      await new Promise((resolve, reject) => {
        ffmpeg.ffprobe(originalVideoPath, (err, metadata) => {
          if (err) {
            console.error(`[${videoId}] 获取视频元数据失败:`, err);
            return reject(err);
          }
          video.duration = metadata.format.duration;
          console.log(`[${videoId}] 获取视频时长: ${video.duration}`);
          resolve();
        });
      });

      // 仅在没有封面图时才自动生成缩略图 (仍然从原始文件生成)
      if (!video.thumbnail) {
        const thumbnailOutputDir = path.join(__dirname, `../../uploads/thumbnails`);
        if (!fs.existsSync(thumbnailOutputDir)) {
          fs.mkdirSync(thumbnailOutputDir, { recursive: true });
        }
        const thumbnailBaseName = path.basename(originalVideoPath, path.extname(originalVideoPath));
        const thumbnailPath = path.join(thumbnailOutputDir, `${thumbnailBaseName}.jpg`);
        await new Promise((resolve, reject) => {
          ffmpeg(originalVideoPath)
            .screenshots({
              timestamps: ['1%'],
              filename: `${thumbnailBaseName}.jpg`,
              folder: thumbnailOutputDir,
              size: '320x?'
            })
            .on('end', resolve)
            .on('error', reject);
        });
        video.thumbnail = `/uploads/thumbnails/${thumbnailBaseName}.jpg`;
        console.log(`[${videoId}] 生成缩略图完成: ${video.thumbnail}`);
      } else {
        console.log(`[${videoId}] 使用现有缩略图: ${video.thumbnail}`);
      }

      // 使用原始视频文件
      const originalFileName = path.basename(originalVideoPath);
      const originalUrl = `/uploads/original/${originalFileName}`;
      try {
        const stats = fs.statSync(originalVideoPath);
        video.formats = [{
          quality: 'original',
          url: originalUrl,
          size: stats.size
        }];
        console.log(`[${videoId}] 视频格式信息更新为原始版本`);
      } catch (statError) {
        console.error(`[${videoId}] 获取原始文件 ${originalVideoPath} 大小失败:`, statError);
        throw statError;
      }

    } catch (processError) { // Changed variable name to avoid conflict
      console.error(`[${videoId}] 处理视频文件信息或压缩失败:`, processError);
      throw new Error('处理视频文件信息或压缩失败');
    }

    // 如果用户是普通用户，视频处理完成后状态设为 'pending' 等待审核
    // 如果用户是管理员，视频处理完成后状态直接设为 'ready'
    const videoUser = await User.findById(video.user);
    if (videoUser && videoUser.role === 'admin') {
      video.status = 'ready';
    } else {
      video.status = 'pending';
      console.log(`[${videoId}] 普通用户上传的视频，设置为待审核状态`);
    }
    video.processingProgress = 100;
    await video.save();
    console.log(`[${videoId}] 视频处理完成（无转码），状态更新为 ${video.status}`);

  } catch (error) {
    console.error('处理视频失败:', error);
    if (video) {
      video.status = 'failed';
      video.errorMessage = error.message;
      await video.save();
    }
  }
};

// 获取基础 URL
const BASE_URL = process.env.BASE_URL || 'http://localhost:3000'; // 从环境变量或默认值获取基础 URL

// Helper function to convert relative paths to absolute URLs
const toAbsoluteUrl = (relativePath) => {
  if (!relativePath || typeof relativePath !== 'string' || relativePath.startsWith('http')) {
    return relativePath; // Return as is if already absolute or invalid
  }
  return `${BASE_URL}${relativePath}`;
};

// Helper function to process video objects for response
const processVideoForResponse = (video) => {
  if (!video) return null;
  const videoObj = video.toObject ? video.toObject() : video; // Ensure it's a plain object

  // 确保每个视频都有formats字段
  if (!videoObj.formats || videoObj.formats.length === 0) {
    // 如果formats为空，基于原始videoUrl创建一个默认format
    videoObj.formats = [{
      quality: 'original',
      url: videoObj.videoUrl,
      size: 0
    }];
  }

  // 处理封面URL，确保有默认值
  if (!videoObj.thumbnail || videoObj.thumbnail === '') {
    // 如果没有封面，使用默认封面
    videoObj.thumbnail = '/uploads/thumbnails/default.jpg';
  }
  
  // Convert thumbnail URL
  videoObj.thumbnail = toAbsoluteUrl(videoObj.thumbnail);

  // Convert format URLs
  if (videoObj.formats && Array.isArray(videoObj.formats)) {
    videoObj.formats = videoObj.formats.map(format => ({
      ...format,
      url: toAbsoluteUrl(format.url)
    }));
  }
  
  // Convert user avatar URL if populated and map user to channel
  if (videoObj.user) {
    // Convert avatar URL
    if (videoObj.user.avatar) {
        videoObj.user.avatar = toAbsoluteUrl(videoObj.user.avatar);
    }
    // Map user to channel for frontend compatibility
    videoObj.channel = {
      id: videoObj.user._id,
      name: videoObj.user.username, 
      avatar: videoObj.user.avatar
    };
  }

  // Convert comment user avatar URLs if populated
  if (videoObj.comments && Array.isArray(videoObj.comments)) {
    videoObj.comments = videoObj.comments.map(comment => {
      if (comment.user && comment.user.avatar) {
        comment.user.avatar = toAbsoluteUrl(comment.user.avatar);
      }
      return comment;
    });
  }

  // Convert preview thumbnail URLs
  videoObj.previewThumbnails = toAbsoluteUrl(videoObj.previewThumbnails);
  videoObj.previewVtt = toAbsoluteUrl(videoObj.previewVtt);

  return videoObj;
};

// Helper function to process an array of video objects
const processVideosForResponse = (videos) => {
  if (!Array.isArray(videos)) return [];
  return videos.map(processVideoForResponse);
};

// 处理视频上传请求
async function uploadVideo(req, res) {
  // 添加详细日志
  console.log('--- Handling video upload request ---');
  console.log('User:', req.user ? req.user._id : 'No user found');
  console.log('Body:', JSON.stringify(req.body, null, 2));
  console.log('Files:', JSON.stringify(req.files, null, 2));
  console.log('Video Info:', JSON.stringify(req.videoInfo, null, 2)); 

  let newVideo = null;
  try {
    const { title, description, category, tags, privacy } = req.body;
    // 检查 userId 是否存在
    if (!req.user || !req.user._id) {
      console.error('Error: User ID not found in request.');
      return res.status(401).json({ error: '用户未认证或认证信息丢失' });
    }
    const userId = req.user._id;

    // 检查是否有文件上传
    if (!req.files || !req.files.video || req.files.video.length === 0) {
      return res.status(400).json({ error: '请选择要上传的视频文件' });
    }

    const videoFile = req.files.video[0];
    const thumbnailFile = req.files.thumbnail ? req.files.thumbnail[0] : null;

    let categoryName = category; 
    if (category === '1') { 
      categoryName = '娱乐'; 
      console.warn("Temporary mapping: Received category '1', mapped to '娱乐'. Fix required.");
    }
  

    
    const parsedTags = JSON.parse(tags || '[]');

  
    let thumbnailPath = null;
    if (thumbnailFile) {
      thumbnailPath = `/uploads/thumbnails/${thumbnailFile.filename}`;
      console.log('使用用户上传的缩略图:', thumbnailPath);
    }

    // 创建新的视频文档
    newVideo = new Video({
      user: userId,
      title,
      description,
      category: categoryName, 
      tags: parsedTags, 
      privacy,
      // 普通用户上传的视频初始状态为 'uploading'，后续会改为 'pending' 等待审核
      status: 'uploading',
      processingProgress: 0,
      duration: req.videoInfo?.duration || 0,
      width: req.videoInfo?.width || 0,
      height: req.videoInfo?.height || 0,
      thumbnail: thumbnailPath, // 使用处理过的缩略图路径
      originalPath: videoFile.path,
      // Add missing required fields
      fileName: videoFile.filename, 
      videoUrl: `/uploads/videos/original/${videoFile.filename}` 
    });

    await newVideo.save();

    // 检查是否为管理员并且要求立即发布
    if (req.user.role === 'admin' && req.body.publishImmediately === 'true') {
      newVideo.status = 'ready';
      newVideo.processingProgress = 100;
    
      if (!newVideo.formats || newVideo.formats.length === 0) {
        newVideo.formats = [{
          quality: 'original',
          url: newVideo.videoUrl, // 使用已保存的 videoUrl
          size: fs.existsSync(videoFile.path) ? fs.statSync(videoFile.path).size : 0 // 获取原始文件大小
        }];
      }
      
      await newVideo.save();
      console.log(`管理员 ${req.user._id} 立即发布视频 ${newVideo._id}`);
      res.status(201).json({ 
        message: '视频上传成功并已直接发布!', 
        videoId: newVideo._id,
        status: 'ready',
        video: processVideoForResponse(newVideo) // 返回处理后的视频对象
      });
    } else {
      // 更新状态为处理中
      newVideo.status = 'processing';
      await newVideo.save();

      // 异步处理视频转码
      processVideo(newVideo._id, videoFile.path).catch(err => {
      console.error(`视频处理失败 (ID: ${newVideo._id}):`, err);
      // 更新视频状态为处理失败
      Video.findByIdAndUpdate(newVideo._id, { 
        status: 'failed', 
        errorMessage: err.message,
        processingProgress: 0
      }).catch(console.error);
    });

      res.status(201).json({ 
        message: '视频上传成功，正在处理中...', 
        videoId: newVideo._id,
        status: 'processing'
      });
    }

  } catch (error) {
    console.error('视频上传处理失败:', error);
    
    // 如果视频文档已创建，删除它
    if (newVideo?._id) {
      try {
        await Video.findByIdAndDelete(newVideo._id);
      } catch (err) {
        console.error('删除失败的视频记录时出错:', err);
      }
    }

    // 清理上传的文件
    if (req.cleanupUpload) {
      req.cleanupUpload();
    }

    res.status(500).json({ 
      error: '视频上传失败，请稍后重试',
      details: error.message
    });
  }
}

// 获取推荐视频
async function getRecommendedVideos(req, res) {
  try {
    const limit = parseInt(req.query.limit) || 10;
    // 引入随机排序，确保每次刷新顺序都变化
    const videos = await Video.find({ status: 'ready', privacy: 'public' })
      .sort({ views: -1 }) // 首先按观看次数排序获取热门视频
      .limit(limit * 2) // 获取更多视频以便随机选择
      .populate('user', 'username avatar');

    // 随机打乱视频顺序
    const shuffledVideos = videos
      .sort(() => Math.random() - 0.5) // 随机排序
      .slice(0, limit); // 截取需要的数量
      
    console.log(`已为推荐视频应用随机排序，返回 ${shuffledVideos.length} 个视频`);
    res.json({ videos: processVideosForResponse(shuffledVideos) }); // Process URLs before sending
  } catch (error) { 
    console.error('获取推荐视频失败:', error);
    res.status(500).json({ error: '获取推荐视频失败' });
  }
}

// 获取热门视频
async function getTrendingVideos(req, res) {
  try {
    const limit = parseInt(req.query.limit) || 10
    const period = req.query.period || 'today' // today, week, month
    let startDate
    const now = new Date()

    switch (period) {
      case 'week':
        startDate = new Date(now.setDate(now.getDate() - 7))
        break
      case 'month':
        startDate = new Date(now.setMonth(now.getMonth() - 1))
        break
      case 'today':
      default:
        startDate = new Date(now.setHours(0, 0, 0, 0))
        break
    }

    // TODO: 实现更精确的热门度计算（例如结合观看次数、点赞、评论、时间）
    const videos = await Video.find({
      status: 'ready',
      privacy: 'public',
      createdAt: { $gte: startDate }
    })
      .sort({ views: -1 }) // 暂时按观看次数排序
      .limit(limit)
      .populate('user', 'username avatar') // 修正为 user
    res.json({ videos: processVideosForResponse(videos) }) 
  } catch (error) {
    console.error('获取热门视频失败:', error)
    res.status(500).json({ error: '获取热门视频失败' })
  }
}

// 获取最新视频
async function getLatestVideos(req, res) {
  try {
    const limit = parseInt(req.query.limit) || 10;
    // 恢复 status: 'ready' 查询条件
    const videos = await Video.find({ status: 'ready', privacy: 'public' })
      .sort({ createdAt: -1 })
      .limit(limit)
      .populate('user', 'username avatar'); // 修正为 user

    res.json({ videos: processVideosForResponse(videos) }); 
  } catch (error) {
    console.error('获取最新视频失败:', error);
    res.status(500).json({ error: '获取最新视频失败' });
  }
}

// 根据分类获取视频
async function getVideosByCategory(req, res) {
  try {
    const category = req.params.categoryName
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 10
    const skip = (page - 1) * limit
    const sortBy = req.query.sort || 'latest' 
    const timeRange = req.query.time || 'all' 
    const tags = req.query.tags ? req.query.tags.split(',') : [] 

    const query = {
      status: 'ready',
      privacy: 'public',
      category: category
    }

    // 添加标签过滤
    if (tags.length > 0) {
      query.tags = { $in: tags } 
    }

    // 添加时间范围过滤
    if (timeRange !== 'all') {
      let startDate
      const now = new Date()
      switch (timeRange) {
        case 'today': startDate = new Date(now.setHours(0, 0, 0, 0)); break;
        case 'week': startDate = new Date(now.setDate(now.getDate() - 7)); break;
        case 'month': startDate = new Date(now.setMonth(now.getMonth() - 1)); break;
        case 'year': startDate = new Date(now.setFullYear(now.getFullYear() - 1)); break;
      }
      if (startDate) query.createdAt = { $gte: startDate }
    }

    // 设置排序
    let sortOption = { createdAt: -1 } // 默认最新
    if (sortBy === 'popular') {
      sortOption = { views: -1 } // 最多观看
    } else if (sortBy === 'trending') {
      // TODO: 实现更复杂的热度排序逻辑 (结合观看、点赞、评论、时间等)
      sortOption = { views: -1 } // 暂时也按观看次数
    }

    const totalVideos = await Video.countDocuments(query)
    const videos = await Video.find(query)
      .sort(sortOption) // 应用排序
      .skip(skip)
      .limit(limit)
      .populate('user', 'username avatar') // 修正为 user

    res.json({
      videos: processVideosForResponse(videos), // Process URLs before sending
      currentPage: page,
      totalPages: Math.ceil(totalVideos / limit),
      totalVideos
    })
  } catch (error) {
    console.error(`获取分类 ${req.params.categoryName} 视频失败:`, error)
    res.status(500).json({ error: '获取分类视频失败' })
  }
}

// 搜索视频
async function searchVideos(req, res) {
  try {
    const query = req.query.q || '';
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;
    const sortBy = req.query.sort || 'relevance'; // relevance, date, views
    const timeRange = req.query.time || 'all'; // all, hour, today, week, month, year
    const duration = req.query.duration || 'any'; // any, short (<4min), long (>20min)
    const type = req.query.type || 'all'; // all, video, channel, playlist

    console.log(`搜索视频，关键词: "${query}"`);

    if (!query) {
      // 如果没有搜索关键词，返回最新视频
      const videos = await Video.find({ 
        status: 'ready', 
        privacy: 'public' 
      })
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(limit)
        .populate('user', 'username avatar');

      return res.json({
        results: processVideosForResponse(videos),
        type: 'video',
        currentPage: page,
        totalPages: Math.ceil(videos.length / limit) || 1,
        totalResults: videos.length,
        query: ''
      });
    }

    // 使用正则表达式进行模糊匹配（针对中文更有效）
    const regexPattern = new RegExp(query.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'), 'i');
    
    // 第一步：查找匹配关键词的用户
    const matchedUsers = await User.find({ 
      username: regexPattern 
    }).select('_id');
    
    const matchedUserIds = matchedUsers.map(user => user._id);
    console.log(`找到 ${matchedUserIds.length} 个匹配用户名的用户`);

    // 构建主查询条件
    let mongoQuery = {
      status: 'ready',
      privacy: 'public',
      $or: [
        { title: regexPattern },              // 匹配标题
        { description: regexPattern },        // 匹配描述
        { tags: { $in: [regexPattern] } }     // 匹配标签
      ]
    };

    // 如果找到匹配的用户，添加用户条件
    if (matchedUserIds.length > 0) {
      mongoQuery.$or.push({ user: { $in: matchedUserIds } });
    }

    // 时间范围过滤
    if (timeRange !== 'all') {
      let startDate;
      const now = new Date();
      switch (timeRange) {
        case 'hour': startDate = new Date(now.setHours(now.getHours() - 1)); break;
        case 'today': startDate = new Date(now.setHours(0, 0, 0, 0)); break;
        case 'week': startDate = new Date(now.setDate(now.getDate() - 7)); break;
        case 'month': startDate = new Date(now.setMonth(now.getMonth() - 1)); break;
        case 'year': startDate = new Date(now.setFullYear(now.getFullYear() - 1)); break;
      }
      if (startDate) mongoQuery.createdAt = { $gte: startDate };
    }

    // 时长过滤
    if (duration === 'short') {
      mongoQuery.duration = { $lt: 240 }; // 小于 4 分钟
    } else if (duration === 'long') {
      mongoQuery.duration = { $gte: 1200 }; // 大于等于 20 分钟
    }

    // 查询总数
    const totalVideos = await Video.countDocuments(mongoQuery);
    console.log(`搜索到 ${totalVideos} 个相关视频`);

    // 设置排序方式
    let sortOption = {};
    if (sortBy === 'date') {
      sortOption = { createdAt: -1 };
    } else if (sortBy === 'views') {
      sortOption = { views: -1 };
    } else {
      // 'relevance'排序 - 加权排序
      sortOption = { 
        views: -1,      // 高观看量优先
        createdAt: -1,  // 更新视频优先
        likesCount: -1  // 更多点赞优先
      };
    }

    // 执行查询
    const videos = await Video.find(mongoQuery)
      .sort(sortOption)
      .skip(skip)
      .limit(limit)
      .populate('user', 'username avatar bio'); // 填充更多用户信息

    // 为每个视频添加匹配原因信息
    const enhancedResults = videos.map(video => {
      const videoObj = video.toObject ? video.toObject() : video;
      videoObj.matchReason = [];
      
      if (videoObj.title && videoObj.title.match(regexPattern)) {
        videoObj.matchReason.push('标题');
      }
      if (videoObj.description && videoObj.description.match(regexPattern)) {
        videoObj.matchReason.push('描述');
      }
      if (videoObj.tags && videoObj.tags.some(tag => tag.match(regexPattern))) {
        videoObj.matchReason.push('标签');
      }
      if (videoObj.user && videoObj.user.username && videoObj.user.username.match(regexPattern)) {
        videoObj.matchReason.push('用户名');
      }
      
      return videoObj;
    });

    res.json({
      results: processVideosForResponse(enhancedResults),
      type: 'video',
      currentPage: page,
      totalPages: Math.ceil(totalVideos / limit) || 1,
      totalResults: totalVideos,
      query: query, // 返回搜索关键词，方便前端显示
      matchedUsers: matchedUsers.length > 0 // 指示是否匹配到用户
    });

  } catch (error) {
    console.error('搜索视频失败:', error);
    res.status(500).json({ error: '搜索视频失败', details: error.message });
  }
}

// 获取视频详情
async function getVideoDetails(req, res) {
  console.log(`[getVideoDetails] Received request for video ID: ${req.params.videoId}`); // 修正为 videoId
  try {
    const video = await Video.findById(req.params.videoId) // 修正为 videoId
      .populate('user', 'username avatar bio subscribersCount') // 修正为 user
      .populate({
        path: 'comments',
        populate: { path: 'user', select: 'username avatar' }, // 修正为 user
        options: { sort: { createdAt: -1 } } // 按时间倒序排列评论
      });

    console.log(`[getVideoDetails] Found video in DB:`, video ? `Status: ${video.status}, ID: ${video._id}` : 'null'); // 添加日志：记录查询结果

    // 检查视频是否存在
    if (!video) {
      console.warn(`[getVideoDetails] Video not found. ID: ${req.params.videoId}`); // 修正为 videoId
      return res.status(404).json({ error: '视频不存在' });
    }

    // 检查访问权限
    const isOwner = req.user && video.user._id.equals(req.user._id);

    // 如果不是所有者，且视频状态不是 ready，则返回 404
    if (!isOwner && video.status !== 'ready') {
      console.warn(`[getVideoDetails] Video not ready and user is not owner. ID: ${req.params.id}, Status: ${video.status}`);
      return res.status(404).json({ error: '视频未处理完成' });
    }

    // 如果不是所有者，且视频是私有的，则返回 403
    if (!isOwner && video.privacy === 'private') {
      return res.status(403).json({ error: '没有权限访问该视频' });
    }
    // 不对 unlisted 视频做限制，知道链接即可访问

    // 增加观看次数 (考虑防刷机制，例如同一 IP 短时间不重复计算)
    // 仅在视频状态为 ready 时增加观看次数
    if (video.status === 'ready') {
      video.views = (video.views || 0) + 1;
      await video.save();
    }

    // 返回视频详情
    // res.json({ video }); // 旧代码，直接返回 Mongoose 对象
    res.json({ video: processVideoForResponse(video) }); // 使用辅助函数处理后再返回

  } catch (error) {
    console.error('获取视频详情失败:', error);
    // 处理 CastError，返回 404
    if (error.name === 'CastError') {
      return res.status(404).json({ error: '视频 ID 格式无效' });
    }
    res.status(500).json({ error: '获取视频详情失败' });
  }
}

// 更新视频信息
async function updateVideoDetails(req, res) {
  try {
    const videoId = req.params.videoId 
    const userId = req.user._id

    const video = await Video.findById(videoId)

    if (!video) {
      return res.status(404).json({ error: '视频不存在' })
    }

    // 检查用户是否有权限修改
    if (!video.user.equals(userId)) {
      return res.status(403).json({ error: '没有权限修改该视频' })
    }

    const { title, description, category, tags, privacy, thumbnail } = req.body

    // 校验输入
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() })
    }

    video.title = title || video.title
    video.description = description || video.description
    video.category = category || video.category
    video.tags = tags || video.tags
    video.privacy = privacy || video.privacy
    // 如果有新的缩略图上传，则更新
    if (req.files && req.files.thumbnail) {
      // 删除旧缩略图 (如果存在且不是默认图)
      if (video.thumbnail && video.thumbnail !== '/uploads/thumbnails/default.jpg' && fs.existsSync(path.join(__dirname, '../../', video.thumbnail))) {
        try {
          fs.unlinkSync(path.join(__dirname, '../../', video.thumbnail));
          console.log(`删除旧缩略图: ${video.thumbnail}`);
        } catch (err) {
          console.error(`删除旧缩略图失败: ${video.thumbnail}`, err);
        }
      }
      // 设置新缩略图路径
      const newThumbnailPath = `/uploads/thumbnails/${req.files.thumbnail[0].filename}`;
      video.thumbnail = newThumbnailPath;
      console.log(`更新视频缩略图: ${newThumbnailPath}`);
    } else if (thumbnail === '') { // 允许清空缩略图，使用默认
      if (video.thumbnail && video.thumbnail !== '/uploads/thumbnails/default.jpg' && fs.existsSync(path.join(__dirname, '../../', video.thumbnail))) {
        try {
          fs.unlinkSync(path.join(__dirname, '../../', video.thumbnail));
          console.log(`删除旧缩略图: ${video.thumbnail}`);
        } catch (err) {
          console.error(`删除旧缩略图失败: ${video.thumbnail}`, err);
        }
      }
      video.thumbnail = '/uploads/thumbnails/default.jpg';
      console.log('重置为默认缩略图');
    }

    await video.save()
    res.json({ message: '视频信息更新成功', video: processVideoForResponse(video) }) // 使用 processVideoForResponse 处理返回数据

  } catch (error) {
    console.error('更新视频信息失败:', error)
    res.status(500).json({ error: '更新视频信息失败' })
  }
}

// 删除视频
async function deleteVideo(req, res) {
  try {
    const videoId = req.params.id
    const userId = req.user._id

    const video = await Video.findById(videoId)

    if (!video) {
      return res.status(404).json({ error: '视频不存在' })
    }

    // 检查用户是否有权限删除 (视频所有者或管理员)
    const isAdmin = req.user.role === 'admin'
    if (!video.user.equals(userId) && !isAdmin) {
      return res.status(403).json({ error: '没有权限删除该视频' })
    }

    // 删除视频文件和缩略图文件
    const videoPathsToDelete = video.formats.map(f => path.join(__dirname, '../../', f.url));
    
    // 添加封面图路径到删除列表，确保清理所有相关文件
    if (video.thumbnail && video.thumbnail !== '/uploads/thumbnails/default.jpg') {
      videoPathsToDelete.push(path.join(__dirname, '../../', video.thumbnail));
    }
    
    // 检查是否有自动生成的封面（基于文件名模式）
    const videoName = path.basename(video.fileName, path.extname(video.fileName));
    const autoThumbnailPath = path.join(__dirname, '../../uploads/thumbnails', `${videoName}.jpg`);
    if (fs.existsSync(autoThumbnailPath)) {
      videoPathsToDelete.push(autoThumbnailPath);
    }

    videoPathsToDelete.forEach(filePath => {
      if (fs.existsSync(filePath)) {
        try {
          fs.unlinkSync(filePath);
          console.log(`已删除文件: ${filePath}`);
        } catch (err) {
          console.error(`删除文件失败: ${filePath}`, err);
        }
      }
    });

    // 从数据库删除视频记录
    await Video.findByIdAndDelete(videoId)

    // TODO: 从用户、播放列表等关联数据中移除该视频引用

    res.json({ message: '视频删除成功' })

  } catch (error) {
    console.error('删除视频失败:', error)
    res.status(500).json({ error: '删除视频失败' })
  }
}

// 点赞/取消点赞视频
async function likeVideo(req, res) {
  try {
    const videoId = req.params.id
    const userId = req.user._id

    const video = await Video.findById(videoId)
    const user = await User.findById(userId)

    if (!video) {
      return res.status(404).json({ error: '视频不存在' })
    }

    const videoIndexInUserLikes = user.likedVideos.indexOf(videoId)
    const userIndexInVideoLikes = video.likes.indexOf(userId)

    let liked = false
    if (videoIndexInUserLikes === -1 && userIndexInVideoLikes === -1) {
      // 点赞
      user.likedVideos.push(videoId)
      video.likes.push(userId)
      liked = true
    } else {
      // 取消点赞
      if (videoIndexInUserLikes !== -1) {
        user.likedVideos.splice(videoIndexInUserLikes, 1)
      }
      if (userIndexInVideoLikes !== -1) {
        video.likes.splice(userIndexInVideoLikes, 1)
      }
    }

    await user.save()
    await video.save()

    res.json({ liked, likesCount: video.likes.length })

  } catch (error) {
    console.error('点赞/取消点赞失败:', error)
    res.status(500).json({ error: '操作失败' })
  }
}

// 获取视频交互状态（是否点赞、收藏等）
async function getVideoInteractionStatus(req, res) {
  try {
    const videoId = req.params.id;
    // 如果用户未登录，返回默认状态
    if (!req.user) {
      return res.json({
        isLiked: false,
        isSubscribed: false
      });
    }

    const userId = req.user._id;
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: '用户不存在' });
    }

    const video = await Video.findById(videoId).populate('user', 'username');
    if (!video) {
      return res.status(404).json({ error: '视频不存在' });
    }

    // 增强空值检查，确保user.likedVideos存在且是数组
    const isLiked = user.likedVideos && Array.isArray(user.likedVideos) ? 
                    user.likedVideos.includes(videoId) : false;
    
    // 增强空值检查，确保video.user存在且user.subscribedTo存在且是数组
    const isSubscribed = video.user && user.subscribedTo && Array.isArray(user.subscribedTo) ? 
                        user.subscribedTo.some(id => id.equals(video.user._id)) : false;

    res.json({
      isLiked,
      isSubscribed
    });

  } catch (error) {
    console.error('获取视频交互状态失败:', error);
    res.status(500).json({ error: '获取状态失败' });
  }
}


// 获取视频处理状态
async function getVideoStatus(req, res) {
  try {
    const { videoId } = req.params;
    const video = await Video.findById(videoId).select('status processingProgress errorMessage');

    if (!video) {
      return res.status(404).json({ error: '视频不存在' });
    }

    res.json({
      status: video.status,
      progress: video.processingProgress,
      error: video.errorMessage
    });
  } catch (error) {
    console.error('获取视频状态失败:', error);
    res.status(500).json({ error: '获取视频状态失败' });
  }
}

// 新增：管理员获取视频列表（包括非 ready 状态）
async function getVideosForAdmin(req, res) {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;
    const statusFilter = req.query.status; // 获取状态筛选参数

    let query = {};
    if (statusFilter && ['uploading', 'processing', 'ready', 'failed'].includes(statusFilter)) {
      query.status = statusFilter;
    }

    const totalVideos = await Video.countDocuments(query);
    const videos = await Video.find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit)
      .populate('user', 'username avatar');

    res.json({
      videos: processVideosForResponse(videos), // Process URLs before sending
      currentPage: page,
      totalPages: Math.ceil(totalVideos / limit),
      totalVideos,
    });
  } catch (error) {
    console.error('获取管理员视频列表失败:', error);
    res.status(500).json({ error: '获取管理员视频列表失败' });
  }
}

// 获取相关视频
async function getRelatedVideos(req, res) {
    try {
        const videoId = req.params.id;
        const limit = parseInt(req.query.limit) || 10;

        // 获取当前视频信息
        const currentVideo = await Video.findById(videoId);
        if (!currentVideo) {
            return res.status(404).json({ error: '视频不存在' });
        }

        // 构建查询条件
        const query = {
            _id: { $ne: videoId }, // 排除当前视频
            status: 'ready',
            privacy: 'public',
            $or: [
                { category: currentVideo.category }, // 相同分类
                { tags: { $in: currentVideo.tags } } // 相同标签
            ]
        };

        // 获取相关视频
        const relatedVideos = await Video.find(query)
            .sort({ views: -1 }) // 按观看次数排序
            .limit(limit)
            .populate('user', 'username avatar');

        res.json({ videos: processVideosForResponse(relatedVideos) });

    } catch (error) {
        console.error('获取相关视频失败:', error);
        res.status(500).json({ error: '获取相关视频失败' });
    }
}

// 管理员更新视频状态 (审核)
async function updateVideoStatus(req, res) {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  try {
    const videoId = req.params.id;
    const { status } = req.body;

    const video = await Video.findById(videoId);

    if (!video) {
      return res.status(404).json({ error: '视频不存在' });
    }

    // 只有处于 pending 或 failed 状态的视频才能被审核更新状态
    // 或者管理员可以强制更新任何状态？这里假设只能审核 pending/failed
    // if (!['pending', 'failed'].includes(video.status)) {
    //   return res.status(400).json({ error: `不能更新状态为 ${video.status} 的视频` });
    // }

    video.status = status;
    // 如果状态是 'failed' 或 'rejected'，可以考虑记录原因
    if (status === 'failed' || status === 'rejected') {
      video.errorMessage = req.body.reason || '管理员操作'; // 可选：从请求体获取原因
    } else {
      video.errorMessage = null; // 清除错误信息
    }

    // 如果审核通过 (ready)，确保处理进度是 100%
    if (status === 'ready') {
      video.processingProgress = 100;
    }

    await video.save();

    // TODO: 可以添加通知用户的逻辑

    res.json({ message: '视频状态更新成功', video: processVideoForResponse(video) });

  } catch (error) {
    console.error('更新视频状态失败:', error);
    res.status(500).json({ error: '更新视频状态失败' });
  }
}

// 获取视频列表 (公共/管理员通用)
async function getVideos(req, res) {
  const { page = 1, limit = 10, search = '', category = '', status = '' } = req.query;
  const user = req.user; // 来自 optionalAuthMiddleware

  try {
    const query = {};

    // 构建基础查询条件
    if (search) query.title = { $regex: search, $options: 'i' };
    const categoryMap = {
      '1': '娱乐',
      '2': '音乐',
      '3': '游戏',
      '4': '科技',
      '5': '教育',
      '6': '生活',
      '7': '体育',
      '8': '新闻',
      '9': '电影'
    };

    if (category) {
      // 如果传入的 category 是数字，尝试映射为中文名称
      query.category = categoryMap[category] || category;
    }

    // 关键：根据用户角色决定状态过滤
    if (user && user.role === 'admin') {
      // 管理员：如果传入 status 则按 status 过滤，否则不过滤状态
      if (status) query.status = status;
    } else {
      // 非管理员或未登录用户：只显示 'ready' 状态的视频
      query.status = 'ready'; 
      // 如果非管理员也传入了 status 过滤，可以忽略或强制为 'ready'
      // query.status = status === 'ready' ? 'ready' : 'ready'; // 更严格的写法
    }

    const videos = await Video.find(query)
      .populate('user', 'username avatar')
      // .populate('category', 'name') // 如果你的 Video 模型有关联 Category
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .sort({ createdAt: -1 });

    // 使用 helper 函数处理 URL 和格式
    const processedVideos = processVideosForResponse(videos);

    const count = await Video.countDocuments(query);

    res.json({
      videos: processedVideos,
      totalPages: Math.ceil(count / limit),
      currentPage: parseInt(page, 10),
      totalVideos: count
    });

  } catch (error) {
    console.error('Error fetching videos:', error);
    res.status(500).json({ message: '获取视频列表失败' });
  }
};

// 获取用户订阅的视频列表
async function getSubscribedVideos(req, res) {
  const { page = 1, limit = 10, sort = 'latest' } = req.query;
  const userId = req.user._id; // 来自 authMiddleware

  try {
    // 修改 select() 中的字段为 'subscribedTo'
    const user = await User.findById(userId).select('subscribedTo');
    if (!user) {
      return res.status(404).json({ error: '用户不存在' });
    }

    // 修改此处，使用 user.subscribedTo，并直接映射 ID
    const subscribedUserIds = user.subscribedTo.map(userId => userId);

    if (subscribedUserIds.length === 0) {
      return res.json({ videos: [], total: 0, currentPage: 1, totalPages: 1 });
    }

    const query = {
      user: { $in: subscribedUserIds },
      status: 'ready', // 只显示已就绪的视频
      privacy: 'public' // 只显示公开视频
    };

    let sortOption = { createdAt: -1 }; // 默认按最新排序
    if (sort === 'popular') {
      sortOption = { views: -1 }; // 按观看次数排序
    }

    const totalVideos = await Video.countDocuments(query);
    const videos = await Video.find(query)
      .populate('user', 'username avatar') // 填充用户信息
      .sort(sortOption)
      .skip((page - 1) * limit)
      .limit(limit * 1);

    // 使用 helper 函数处理 URL 和格式
    const processedVideos = processVideosForResponse(videos);

    res.json({
      videos: processedVideos,
      total: totalVideos,
      currentPage: parseInt(page, 10),
      totalPages: Math.ceil(totalVideos / limit)
    });

  } catch (error) {
    console.error('获取订阅视频失败:', error);
    res.status(500).json({ error: '获取订阅视频失败' });
  }
}

module.exports = {
  uploadVideo,
  getRecommendedVideos,
  getTrendingVideos,
  getLatestVideos,
  getVideosByCategory,
  searchVideos,
  getVideoDetails,
  updateVideoDetails,
  deleteVideo,
  likeVideo,
  getVideoInteractionStatus,
  getVideoStatus,
  getVideosForAdmin, // 假设这个已存在
  updateVideoStatus, // 假设这个已存在
  getRelatedVideos,
  getVideos, // <--- 现在可以直接引用函数名
  getSubscribedVideos // <--- 添加导出
};